package com.tools.app.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.tools.app.LogUtil;
import com.tools.app.R;


public class RationImageView extends ImageView {
    private int mProportion;  //宽和高的比例

    public RationImageView(Context context) {
        super(context);
    }

    public RationImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RationImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        //获取比例值
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.HWLayout);
        mProportion = a.getInt(R.styleable.HWLayout_proportion,
                800450);//宽高比例：16:9
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));
        int childWidthSize = getMeasuredWidth();

        String s = "" + mProportion;
        int width_pro = Integer.parseInt(s.substring(0, s.length() / 2));  //得到宽的比例
        int height_pro = Integer.parseInt(s.substring(s.length() / 2));       //得到高的比例
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);

        /** * 按照比例改变高度值 */
        heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) (childWidthSize * height_pro * 1.0) / width_pro, MeasureSpec.EXACTLY);

        LogUtil.error("RationImageView widthMeasureSpec " + widthMeasureSpec);
        LogUtil.error("RationImageView heightMeasureSpec " + heightMeasureSpec);

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}